package com.testfan.apitest.fund;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.alibaba.fastjson.JSON;

import autotest.util.ExcelDataUtil;
import autotest.util.JSONPathUtil;
import autotest.util.PropUtil;

public class UserRegError {
	private static Logger log = Logger.getLogger(UserRegError.class.getName());
	private static CloseableHttpClient httpClient = null;
	private Properties prop = PropUtil.getProperties("/config.properties");
	private String host = null;

	@BeforeClass
	public void setUp() {
		host = prop.getProperty("fund-url");
		httpClient = HttpClients.createDefault(); // 创建一个httpclient，用于执行请求
	}

	@DataProvider(name = "regData")
	public Object[][] regData() {
		Object[][] data = ExcelDataUtil.read("/excel/fund-user.xls", "user", 0, 0, 0, 0);
		return data;
	}

	@Test(dataProvider = "regData")
	public void reg(String nickname, String phone, String password, String code)
			throws ClientProtocolException, IOException {
		log.info("reg with:" + nickname + " " + phone + " " + password);
		HttpPost req = new HttpPost(host + "/fund-app/user/regist");

		Map<String, Object> userMap = new HashMap<>();
		userMap.put("nickname", nickname);
		userMap.put("mobile", phone);
		userMap.put("password", password);
		userMap.put("passwordConfirm", password);
		userMap.put("inviteUser", 1);
		String json = JSON.toJSONString(userMap);

		StringEntity entity = new StringEntity(json, "utf-8");
		entity.setContentType("application/json");
		req.setEntity(entity); // 设置请求体

		CloseableHttpResponse res = httpClient.execute(req); // 执行请求
		String resBody = EntityUtils.toString(res.getEntity()); // res.getEntity()拿到响应体对象。
																// EntityUtils.toString将响应体转成字符串形式返回
		log.info("reg: " + resBody);
		String codeRes = "" + JSONPathUtil.extract(resBody, "$.code");
		Assert.assertEquals(codeRes, code);
	}

}
